package com.fj.netty.protocol.custom;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

/**
 * 自定义编解码器
 * @author fj
 * @date 2024/1/11 10:19
 */
public class MessageCodec extends ByteToMessageCodec<Message> {
    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {
        //魔数4
        out.writeBytes(new byte[]{1,2,3,4});
        //版本1
        out.writeByte(1);
        //序列化方式1
        out.writeByte(SerializeAlgorithm.JAVA.ordinal());
        //指令类型1
        out.writeByte(msg.getMessageType());
        //消息顺序4
//        out.writeInt(msg.getSequence());
        out.writeInt(1);
        //补齐12字节1
        out.writeByte(0xFF);
        //长度4
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(msg);
        byte[] byteArray = bos.toByteArray();
        out.writeInt(byteArray.length);
        //内容
        out.writeBytes(byteArray);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int magic = in.readInt();
        byte version = in.readByte();
        byte serialize = in.readByte();
        byte messageType = in.readByte();
        int sequence = in.readInt();
        in.readByte();
        int length = in.readInt();
        byte[] bytes = new byte[length];
        in.readBytes(bytes, 0, length);
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
        Message message = (Message) ois.readObject();
        System.out.println(message);
    }
}
